Routing in MVC
In the ASP.NET Web Forms application, every URL must match with a specific .aspx file. For example, a URL http://domain/studentsinfo.aspx must match with the file studentsinfo.aspx that contains code and markup for rendering a response to the browser.
ASP.NET introduced Routing to eliminate the needs of mapping each URL with a physical file. Routing enables us to define a URL pattern that maps to the request handler. This request handler can be a file or class. In ASP.NET Webform application, request handler is .aspx file, and in MVC, it is the Controller class and Action method. For example, http://domain/students can be mapped to http://domain/studentsinfo.aspx in ASP.NET Webforms, and the same URL can be mapped to Student Controller and Index action method in MVC.
Route
Route defines the URL pattern and handler information. All the configured routes of an application stored in RouteTable and will be used by the Routing engine to determine appropriate handler class or file for an incoming request.
The following figure illustrates the Routing process.
Configure a Route
Every MVC application must configure (register) at least one route configured by the MVC framework by default.
You can register a route in RouteConfig
class, which is in RouteConfig.cs
under App_Start
folder. The following figure illustrates how to configure a route in the RouteConfig
class .
As you can see in the above figure, the route is configured using the MapRoute()
extension method of RouteCollection
, where name is "Default", url pattern is "{controller}/{action}/{id}"
and defaults parameter for controller, action method and id parameter. Defaults specify which controller, action method, or value of id parameter should be used if they do not exist in the incoming request URL.
In the same way, you can configure other routes using the MapRoute()
method of the RouteCollection
class.
This RouteCollection
is actually a property of the RouteTable class.
URL Pattern
The URL pattern is considered only after the domain name part in the URL. For example, the URL pattern "{controller}/{action}/{id}" would look like localhost:1234/{controller}/{action}/{id}. Anything after "localhost:1234/" would be considered as a controller name. The same way, anything after the controller name would be considered as action name and then the value of id parameter.
If the URL doesn't contain anything after the domain name, then the default controller and action method will handle the request. For example, http://localhost:1234
would be handled by the HomeController
and the Index()
method as configured in the default parameter.
The following table shows which Controller, Action method, and Id parameter would handle different URLs considering the above default route.
URL | Controller | Action | Id |
---|---|---|---|
http://localhost/home | HomeController | Index | null |
http://localhost/home/index/123 | HomeController | Index | 123 |
http://localhost/home/about | HomeController | About | null |
http://localhost/home/contact | HomeController | Contact | null |
http://localhost/student | StudentController | Index | null |
http://localhost/student/edit/123 | StudentController | Edit | 123 |
Multiple Routes
You can also configure a custom route using the MapRoute extension method. You need to provide at least two parameters in MapRoute, route name, and URL pattern. The Defaults parameter is optional.
You can register multiple custom routes with different names. Consider the following example where we register "Student" route.
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Student",
url: "students/{id}",
defaults: new { controller = "Student", action = "Index"}
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
As shown in the above code, the URL pattern for the Student
route is students/{id}, which specifies that any URL that starts with domainName/students
, must be handled by the StudentController
.
Notice that we haven't specified {action}
in the URL pattern because we want every URL that starts with students should always use the Index()
action of the StudentController
class. We have specified the default controller and action to handle any URL request, which starts from domainname/students
.
MVC framework evaluates each route in sequence. It starts with the first configured route, and if incoming URL doesn't satisfy the URL pattern of the route, then it will evaluate the second route and so on.
In the above example, routing engine will evaluate the Student
route first and if incoming URL doesn't start with /students
then only it will consider the second route which is the default route.
The following table shows how different URLs will be mapped to the Student
route:
URL | Controller | Action | Id |
---|---|---|---|
http://localhost/student/123 | StudentController | Index | 123 |
http://localhost/student/index/123 | StudentController | Index | 123 |
http://localhost/student?Id=123 | StudentController | Index | 123 |
Route Constraints
You can also apply restrictions on the value of the parameter by configuring route constraints. For example, the following route applies a limitation on the id parameter that the id's value must be numeric.
routes.MapRoute(
name: "Student",
url: "student/{id}/{name}/{standardId}",
defaults: new { controller = "Student", action = "Index", id = UrlParameter.Optional, name = UrlParameter.Optional, standardId = UrlParameter.Optional },
constraints: new { id = @"\d+" }
);
So if you give non-numeric value for id parameter, then that request will be handled by another route or, if there are no matching routes, then "The resource could not be found"
error will be thrown.
Register Routes
Now, after configuring all the routes in the RouteConfig
class,
you need to register it in the Application_Start()
event in the Global.asax
so that it includes all your routes into the RouteTable
.
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
The following figure illustrate Route registration process.
Thus, routing plays important role in MVC framework.
- Routing plays important role in the MVC framework. Routing maps URL to physical file or class (controller class in MVC).
- Route contains URL pattern and handler information. URL pattern starts after the domain name.
- Routes can be configured in RouteConfig class. Multiple custom routes can also be configured.
- Route constraints apply restrictions on the value of parameters.
- Route must be registered in Application_Start event in Global.ascx.cs file.